<template>



	<div class="system-datainterface-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1300px">

			<el-card shadow="hover">
				<el-form :model="state.ruleForm" ref="datainterfaceDialogFormRef" :rules="rules" size="default"
					label-width="80px">
					<el-row :gutter="35">



						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"
							v-if="state.dialog.type === 'edit'">
							<el-form-item label="md5" prop="md5">
								<el-input :disabled.sync="state.dialog.type === 'edit'" v-model="state.ruleForm.md5"
									placeholder="请输入md5" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="接口名称" prop="interfaceName">
								<el-input :disabled.sync="state.dialog.type === 'edit'"
									v-model="state.ruleForm.interfaceName" placeholder="请输入接口名称" clearable></el-input>
							</el-form-item>
						</el-col>


						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="接口类型" prop="interfaceType">
								<el-select v-model="state.ruleForm.interfaceType" placeholder="接口类型" clearable
									class="input-width">
									<el-option key="rest" label="REST服务" value="rest"></el-option>
									<el-option key="sql" label="动态SQL" value="sql"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"
							v-if="state.ruleForm.interfaceType == 'rest'">
							<el-form-item label="访问方式" prop="restMethod">
								<el-select v-model="state.ruleForm.restMethod" placeholder="访问方式" clearable
									class="input-width">
									<el-option key="post" label="post" value="post"></el-option>
									<el-option key="get" label="get" value="get"></el-option>
									<el-option key="put" label="put" value="put"></el-option>
									<el-option key="delete" label="delete" value="delete"></el-option>
								</el-select>
							</el-form-item>
						</el-col>



						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="授权方式" prop="authMethod">
								<el-select v-model="state.ruleForm.authMethod" placeholder="授权方式" clearable
									class="input-width">
									<el-option key="NOAUTH" label="不用授权" value="NOAUTH"></el-option>
									<el-option key="ALLSYSTEMUSER" label="需登录" value="ALLSYSTEMUSER"></el-option>
									<el-option key="BYUSERPERMISSION" label="需授权" value="BYUSERPERMISSION"></el-option>
								</el-select>
							</el-form-item>
						</el-col>





						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="所属服务" prop="microServiceName">
								<el-select v-model="state.ruleForm.microServiceName" placeholder="所属服务" clearable
									class="input-width">
									<el-option v-for="item in state.microServiceList" :key="item.dicItemValue"
										:label="item.dicItemName" :value="item.dicItemValue"></el-option>
								</el-select>
							</el-form-item>
						</el-col>


						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="状态" prop="status">
								<el-select clearable v-model.number="state.ruleForm.status">
									<el-option v-for="item in state.statusList" :key="item.dicItemValue"
										:label="item.dicItemName" :value="parseInt(item.dicItemValue)" />
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="内容" prop="urlOrSqlContent">
								<el-input type="textarea" :autosize="{ minRows: 4, maxRows: 20 }"
									v-model="state.ruleForm.urlOrSqlContent" placeholder="内容" clearable></el-input>
							</el-form-item>
						</el-col>

					</el-row>
				</el-form>


			</el-card>

			<el-card style="margin-top: 20px;" shadow="hover">
				<div class="bar_tools">
					<div>参数列表</div>
					<el-button-group class="ml-4">
						<el-button type="primary" size="default" @click="handleAdd()">添加</el-button>
					</el-button-group>
				</div>

				<el-form size="default" ref="datainterfaceDataParmsForm" :model="state.ruleForm" label-width="0px">

					<el-table size="default" :data="state.ruleForm.params" style="width: 100%">
						<el-table-column label="序号" prop="seq" width="180">
							<template #default="scope">
								<el-form-item :prop="'params.' + scope.$index + '.seq'"
									:rules="state.itemsRule.seqRule">
									<el-input-number v-model.number="scope.row.seq" :step="5" step-strictly size="small"
										:min="0" :max="1000" inline></el-input-number>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column label="字段名称">
							<template #default="scope">
								<div>
									<el-form-item :prop="'params.' + scope.$index + '.fieldName'"
										:rules="state.itemsRule.commonRule">
										<el-input style="width:150" v-model="scope.row.fieldName" placeholder="" />
									</el-form-item>
								</div>
							</template>
						</el-table-column>


						<el-table-column label="数据类型" prop="fieldType" width="150">
							<template #default="scope">
								<el-form-item>
									<el-select clearable v-model="scope.row.fieldType">
										<el-option v-for="item in state.fieldTypeList" :key="item.name"
											:label="item.label" :value="item.name" autocomplete="on" />
									</el-select>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column label="描述">
							<template #default="scope">
								<div>
									<el-form-item>
										<el-input style="width:150" v-model="scope.row.description" placeholder="" />
									</el-form-item>
								</div>
							</template>
						</el-table-column>

						<el-table-column label="状态" prop="status" width="120">
							<template #default="scope">
								<el-form-item>
									<el-select v-model="scope.row.status" width="100" autocomplete="on"
										value-key="dicItemValue">
										<el-option v-for="item in state.statusList" :key="item.dicItemValue"
											:label="item.dicItemName" :value="parseInt(item.dicItemValue)"
											autocomplete="on" />
									</el-select>
								</el-form-item>
							</template>
						</el-table-column>


						<el-table-column label="操作" width="100">
							<template #default="scope">
								<el-button-group>
									<el-button type="primary" size="small" v-if="scope.row.dicItemId == null"
										@click="handleRemove(scope.$index)">移除
									</el-button>
								</el-button-group>
							</template>
						</el-table-column>



					</el-table>

				</el-form>
			</el-card>




			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script setup lang="ts" name="systemDicDialog">
import { ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';




// 导入接口
import { useSysApi } from "../../../api/sys";


const datainterfaceDialogFormRef = ref();
const datainterfaceDataParmsForm = ref();


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);


const rules = {
	interfaceName: [
		{ required: true, message: "请输入接口名称", trigger: "blur" },
		{
			min: 5,
			max: 100,
			message: "长度在 5 到 100 个字符",
			trigger: "blur"
		}
	],
	urlOrSqlContent: [
		{ required: true, message: "请输入接口内容", trigger: "blur" },
		{
			min: 10,
			max: 50000,
			message: "长度在 10 到 5000 个字符",
			trigger: "blur"
		}
	],
	status: [
		{ required: true, message: "请选择状态", trigger: "blur" }
	]
}


const state = reactive({
	_id: "",
	itemsRule: {
		commonRule: [
			{
				required: true,
				message: "不能为空，请重新输入！",
				trigger: "blur"
			},
			{
				min: 2,
				max: 100,
				message: "长度在 2 到 100 个字符",
				trigger: "blur"
			}
		],
		seqRule: [
			{ required: true, message: "请输入", trigger: "blur" },
			{ type: "number", message: "必须为数字值" }
		]
	},
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		md5: "",
		interfaceName: "",
		interfaceType: "",
		microServiceName: "",
		authMethod: "",
		urlOrSqlContent: "",
		restMethod: "",
		status: "",
		params: [] as any
	},
	fieldTypeList: [
		{ name: "String", label: "字符" },
		{ name: "Double", label: "数字" },
		{ name: "Date", label: "日期时间" },
		{ name: "Integer", label: "整型" },
		{ name: "Boolean", label: "布尔型" },
		{ name: "Long", label: "长整型" }
	],
	statusList: [] as any,
	microServiceList: [] as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});



const handleAdd = () => {
	state.ruleForm.params.push({
		isNew: true,
		status: 1,
		fieldType: "String"
	});
}

const handleRemove = (index: any) => {
	state.ruleForm.params.splice(index, 1);
}


// 打开弹窗
const openDialog = async (type: string, row?: any) => {
	if (type === 'edit') {
		console.log(row)


		state.ruleForm = {
			md5: row.md5,
			interfaceName: row.interfaceName,
			interfaceType: row.interfaceType,
			microServiceName: row.microServiceName,
			authMethod: row.authMethod,
			urlOrSqlContent: row.urlOrSqlContent,
			restMethod: row.restMethod,
			status: row.status,
			params: row.params
		}

		state._id = row._id;






		state.dialog.title = '修改数据接口';
		state.dialog.submitTxt = '修 改';
	} else {


		state.ruleForm = {
			md5: "",
			interfaceName: "",
			interfaceType: "sql",
			microServiceName: "General",
			authMethod: "ALLSYSTEMUSER",
			urlOrSqlContent: "",
			restMethod: "",
			status: "",
			params: [] as any
		}




		state.dialog.title = '新增数据接口';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {



	// 检查顶层表单
	datainterfaceDialogFormRef.value.validate((valid: any) => {
		if (valid) {
			//检查参数列表

			// 检查顶层表单
			datainterfaceDataParmsForm.value.validate(async (valid: any) => {
				if (valid) {
					//检查参数列表

					let datainterfaceData = {
						interfaceName: state.ruleForm.interfaceName,
						interfaceType: state.ruleForm.interfaceType,
						microServiceName: state.ruleForm.microServiceName,
						authMethod: state.ruleForm.authMethod,
						urlOrSqlContent: state.ruleForm.urlOrSqlContent,
						restMethod: state.ruleForm.restMethod,
						status: state.ruleForm.status,
						params: state.ruleForm.params
					}

					if (state.ruleForm.md5) datainterfaceData["md5"] = state.ruleForm.md5;
					if (state._id) datainterfaceData["_id"] = state._id;





					try {
						await useSysApi().dataInterfaceSaveOrUpdate([datainterfaceData]);
						ElMessage.success("操作成功");
						closeDialog(); // 关闭弹窗
						emit('refresh');
					} catch (error: any) {
						ElMessage.error("操作失败请稍后再试");
					}


				} else {
					ElMessage.warning("请检查数据的正确性！");
				}
			})


		} else {
			ElMessage.warning("请检查数据的正确性！");
		}
	})







	// closeDialog(); // 关闭弹窗
	// emit('refresh');
	// if (state.dialog.type === 'add') { }
	// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};




const selectDicItemsByDicCode = async () => {
	state.statusList = await useSysApi().selectDicItemsByDicCode("commStatus", "General");
	state.microServiceList = await useSysApi().selectDicItemsByDicCode("microServiceList", "General");
}


watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
			selectDicItemsByDicCode();
		}
	}, { immediate: true }
);




// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss">
.el-select {
	width: 100% !important;
}



.system-datainterface-dialog-container {
	.bar_tools {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.el-table__expanded-cell {
		padding: 20px;
	}
}
</style>